<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="../index.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        canvas {
            margin: 50px auto 0;
            display: block;
            background: yellow;
        }
    </style>
</head>
<body>
<canvas id="canvas" width="400" height="400">
    此浏览器不支持canvas
</canvas>
</body>
</html>
<script>
    const ctx = document.getElementById('canvas')
    const gl = ctx.getContext('webgl')

    const VERTEX_SHADER_SORUCE = `
    attribute vec4 aPosition;
    uniform mat4 mat;
    void main(){
      gl_Position = mat * aPosition;
      gl_PointSize = 10.0;
    }
  `;
    const FRAGEMNT_SHADER_SOURCE = `
    void main(){
      gl_FragColor = vec4(1.0,0.0,0.0,1.0);
    }
  `;
    // 封装后
    const program = initShader(gl, VERTEX_SHADER_SORUCE, FRAGEMNT_SHADER_SOURCE)
    const aPosition = gl.getAttribLocation(program, 'aPosition')
    const mat = gl.getUniformLocation(program, 'mat')

    // 绕z轴旋转
    function getRotateMatrix(deg) {
        return new Float32Array([
            Math.cos(deg), Math.sin(deg), 0.0, 0.0,
            -Math.sin(deg), Math.cos(deg), 0.0, 0.0,
            0.0, 0.0, 1.0, 0.0,
            0.0, 0.0, 0.0, 1,
        ])
    }

    // 顶点数据
    const points = new Float32Array([
        -0.5, -0.5,
        0.5, -0.5,
        0.0, 0.5,
    ])
    const buffer = gl.createBuffer();

    gl.bindBuffer(gl.ARRAY_BUFFER, buffer)

    gl.bufferData(gl.ARRAY_BUFFER, points, gl.STATIC_DRAW)

    gl.vertexAttribPointer(aPosition, 2, gl.FLOAT, false, 0, 0)
    // 激活aPosition
    gl.enableVertexAttribArray(aPosition)

    let deg = 0;
    let translateX = -1;
    let scaleX = 0.1;

    function animation() {
        deg += 0.01;
        translateX += 0.01;
        scaleX += 0.01;

        if (translateX > 1) {
            translateX = -1;
        }
        if (scaleX > 1.5) {
            scaleX = 0.1
        }

        const translate = getTranslateMatrix(translateX)
        const scale = getScaleMatrix(scaleX)
        const rotate = getRotateMatrix(deg)
        // gl.vertexAttrib1f(aTranslate, x)
        const matrix = mixMatrix(mixMatrix(translate,scale),rotate)
        gl.uniformMatrix4fv(mat, false, matrix)
        gl.drawArrays(gl.TRIANGLES, 0, 3);
        requestAnimationFrame(animation)
    }

    animation()
</script>
